<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021/8/31
 * Time: 9:07
 */
namespace app\admin\controller;

use app\BaseController;
use app\middleware\AdminCheck;
use Firebase\JWT\JWT;
use think\facade\Db;

class Manager extends BaseController{

    protected $middleware = [
        AdminCheck::class => ['except' 	=> ['login'] ]
    ];


    /**
     * 管理员登录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(){
        validateParam('username,password','username,password');
        $username=input('username');
        $password=input('password');
        $manager=Db::name('system_admin')
            ->where(['username'=>$username,'password'=>sp_password($password),'is_deleted'=>0])
            ->find();
        if(empty($manager)){
            return error('账号密码错误');
        }
        //判断是否禁用状态
        if($manager['status'] == 1){
            return error('账号已被禁用，请联系超管！');
        }
        //写入操作日志
        writeSystemLog($manager['id'],'login','登录成功');
        //更新上一次的登录时间
        Db::name('system_admin')
            ->where(['id'=>$manager['id']])
            ->update(['last_login_time'=>currentTime()]);

        //生成token
        $expire_time = strtotime('+30 day');
        $token_arr = [
            'user_id' => $manager['id'],
            'expire_time' => $expire_time//token的过期时间为十天
        ];
        $key = config('system.tokenAdminKey');
        $jwt_token = JWT::encode($token_arr, $key);

        return success('登录成功',['token'=>$jwt_token]);
    }


    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(){
        $manager=Db::name('system_admin')
            ->field('id,username,avatar,real_name,email,phone')
            ->where(['id'=>UID])
            ->find();
        $manager['roles']=['admin'];
        return success('管理员资料',$manager);
    }


    /**
     * 退出登录
     * @return \think\response\Json
     */
    public function logout(){
        return success('退出登录成功');
    }


    /**
     * 获取当前用户的树状菜单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function menuList(){
        $manager=Db::name('system_admin')
            ->where(['id'=>UID])
            ->find();//获取管理员的角色的id
        //根据用户名判断超级管理员
        if($manager['username'] === 'admin'){
            $list=Db::name('system_menu')
                ->order('sort desc')
                ->select()->toArray();
        }else{
            $role_id=$manager['role_id'];
            //通过角色id获取对应的角色的menu_id
            $menu_ids=Db::name('system_role')
                ->where(['id'=>$role_id])
                ->value('menu_ids');
            $menu_ids = json_decode($menu_ids,true);
            $list=Db::name('system_menu')
                ->where('id','in',$menu_ids)
                ->order('sort desc')
                ->select()->toArray();
        }
        //循环list
        foreach ($list as $k=>$v){
            $list[$k]['meta'] = json_decode($v['meta'],true);
        }
        $menu=getMenuTree($list);
        $path=$menu[0]['path'];
        if($path !== '/'){
            $menu[0]['path'] = '/';
        }
        return success('当前用户的菜单列表',['list'=>$menu]);
    }


    /**
     * 管理员列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function managerList(){
        validateParam('pageNo,pageSize,username','pageNo,pageSize');
        $input=input();
        $where[]=['is_deleted','=',0];
        if(!empty($input['username'])){
            $where[]=['username','like',"%{$input['username']}%"];
        }
        //获取总数量
        $total=Db::name('system_admin')
            ->where($where)
            ->order('create_at desc')
            ->count();

        $offset=makeOffset($input['pageNo'],$input['pageSize']);

        $list=Db::name('system_admin')
            ->where($where)
            ->order('create_at desc')
            ->limit($offset,$input['pageSize'])
            ->select()->toArray();
        //循环获取角色的信息
        foreach ($list as $k=>$v){
            if($v['username'] == 'admin'){
                $list[$k]['role_name']='超级管理员';
            }else{
                $role=Db::name('system_role')
                    ->where('id',$v['role_id'])
                    ->find();
                if(!empty($role)) {
                    $list[$k]['role_name'] = $role['label'];
                }else{
                    $list[$k]['role_name'] = '角色已被删除';
                }
            }
        }

        return success('管理员列表',['list'=>$list,'total'=>$total]);
    }


    /**
     * 角色列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function roleList(){
        $list=Db::name('system_role')
            ->field('id as role_id,label as role_name')
            ->select();
        return success('角色列表',$list);
    }


    /**
     * 添加管理员
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(){
        validateParam('username,password,avatar,role_id','username,password,avatar,role_id');
        $input=input();
        if($input['username'] === 'admin'){
            return error('不可使用admin用户名');
        }
        //判断管理员的用户名是否重复
        $admin=Db::name('system_admin')
            ->where(['username'=>$input['username'],'is_deleted'=>0])
            ->find();
        if(!empty($admin)) {
            return error('用户名重复');
        }
        $input['password']=sp_password($input['password']);
        $input['create_at']=currentTime();
        $input['update_at']=currentTime();
        Db::name('system_admin')
            ->insert($input);
        return success('添加管理员成功');
    }


    /**
     * 管理员编辑(超管操作)
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(){
        validateParam('id','id');
        $input=input();
        $data=[];
        if(isset($input['username']) && !empty($input['username'])) {
            //首先判断用户名是否重复
            $admin = Db::name('system_admin')
                ->where('id', '<>', $input['id'])
                ->where('username', $input['username'])
                ->find();
            if (!empty($admin)) {
                return error('用户名重复');
            }
            $data['username']=$input['username'];
        }
        if(isset($input['password']) && !empty($input['password'])){
            $data['password']=sp_password($input['password']);
        }
        if(isset($input['avatar']) && !empty($input['avatar'])){
            $data['avatar']=$input['avatar'];
        }
        if(isset($input['role_id']) && !empty($input['role_id'])){
            $data['role_id']=$input['role_id'];
        }
        $data['id']=$input['id'];
        $data['update_at']=currentTime();
        Db::name('system_admin')
            ->save($data);
        return success('编辑管理员成功');
    }


    /**
     * 管理员自己编辑个人信息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function editInfo(){
        $param=input();
        $data=[];
        if(isset($param['real_name']) && !empty($param['real_name'])){
            $data['real_name']=$param['real_name'];
        }

        if(isset($param['email']) && !empty($param['email'])){
            $data['email']=$param['email'];
        }

        if(isset($param['phone']) && !empty($param['phone'])){
            $data['phone']=$param['phone'];
        }

        if(isset($param['password']) && !empty($param['password'])){
            $data['password']=sp_password($param['password']);
        }

        if(isset($param['avatar']) && !empty($param['avatar'])){
            $data['avatar']=$param['avatar'];
        }

        if(!empty($data)) {
            Db::name('system_admin')
                ->where('id', '=', uid())
                ->update($data);
        }else{
            return error('至少填写一个指定的参数');
        }

        return success('更新信息成功');
    }


    /**
     * 删除管理员
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete(){
        validateParam('ids','ids');
        if(!is_array(input('ids'))){
            return error('参数错误：ids为数组类型');
        }
        if(empty(input('ids'))){
            return error('参数错误：ids不能为空');
        }
        Db::name('system_admin')
            ->where('id','in',input('ids'))
            ->delete();
        return success('删除管理员成功');
    }


    /**
     * 系统操作日志
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function systemLog(){
        validateParam('pageSize,pageNo,username,searchDate','pageSize,pageNo');
        $param=input();
        $where=[];
        if(!empty($param['username'])){
            $where[]=['b.username','=',$param['username']];
        }

        if(!empty($param['searchDate'])){
            $where[]=['a.create_at','between',$param['searchDate']];
        }

        $offset=makeOffset($param['pageNo'],$param['pageSize']);
        $total=Db::name('system_operate_log')
            ->alias('a')
            ->leftJoin('system_admin b','a.admin_id=b.id')
            ->where($where)
            ->count();

        $list=Db::name('system_operate_log')
            ->field('a.id,a.type,a.execute_result,a.user_agent,a.ip,a.create_at,b.username,b.real_name')
            ->alias('a')
            ->leftJoin('system_admin b','a.admin_id=b.id')
            ->where($where)
            ->order('create_at desc')
            ->limit($offset,$param['pageSize'])
            ->select();

        return success('系统操作日志',['total'=>$total,'list'=>$list]);
    }


}